package controller.material;

import java.sql.SQLException;
import java.util.ArrayList;

import service.CoffeeService;
import to.BeansTO;
import util.CoffeeUtil;

public class Material extends Thread {
	private CoffeeService service;

	public Material(CoffeeService service) {
		this.service = service;
	}

	@Override
	public void run() {
		while (true) {
			int beansTotalWeight = 0;
			try {
				beansTotalWeight = service.selectMaterialTotalWeight("원두");
			} catch (SQLException e) {
				e.printStackTrace();
			}
			if (CoffeeUtil.BEANS_TOTAL_WEIGHT > beansTotalWeight) {// 가진 총 중량이
				BeansTO bean = Tally(Warehousing());
				// bean 입고 insert
				String str = CoffeeUtil.getNow();
				bean.setDate(str);
				try {
					System.out.println("원두입고중");
					CoffeeUtil.sleep(CoffeeUtil.MATERIAL_INPUT_TIME);
					service.insertBeansInfo(bean);
				} catch (SQLException e) {
					e.printStackTrace();
				}
				// 총중량 업데이트 bean.getWeight()
				try {
					service.updateMaterialTotalWeight("원두", bean.getWeight());
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}

	}

	static public ArrayList<BeansTO> Warehousing() {
		ArrayList<BeansTO> list = new ArrayList<BeansTO>();
		list.add(new BeansTO());
		list.add(new BeansTO());
		list.add(new BeansTO());
		return list;
	}

	static public BeansTO Tally(ArrayList<BeansTO> list) {
		BeansTO beans = new BeansTO();
		for (BeansTO ben : list) {
			ben.setUnitCost(ben.getCost() / ben.getWeight());
			char c = ((char) ((Math.random() * 3) + 65));
			System.out.println(String.valueOf(c));
			ben.setQuality(String.valueOf(c));
			ben.setForeign((int) ((Math.random() * 5) + 2));
			Evaluation(ben);
			System.out.println(ben);
		}
		for (BeansTO ben : list) {
			if (beans.getEvaluationGrade() < ben.getEvaluationGrade()) {
				beans = ben;
			}
		}
		// System.out.println(beans);
		return beans;
	}

	static public void Evaluation(BeansTO ben) {
		double quality = 0;
		switch (ben.getQuality()) {
		case "A":
			quality = 1;
			break;
		case "B":
			quality = 0.8;
			break;
		case "C":
			quality = 0.5;
			break;
		}
		ben.setEvaluationGrade((ben.getCost() / (ben.getWeight() - (ben
				.getWeight() * (ben.getForeign() * 0.01)))) * quality);
	}

}
